<?php

namespace App\Exports;

use App\Models\AgentTopUpOrder;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;

class FztPaymentOrderStatusExport extends DefaultValueBinder implements FromArray, WithHeadings, WithCustomValueBinder
{
    use Exportable;

    private $batchNumber;

    /**
     * 银行订单状态
     */
    const STAT_MAP = [
        '待支付',
        '已支付',
    ];

    public function __construct($batchNumber)
    {
        $this->batchNumber = $batchNumber;
    }

    public function headings(): array
    {
        return [
            '订单号',
            '代理昵称',
            '代理姓名',
            '代理手机号',
            '银行订单状态',
            '商品订单状态',
        ];
    }

    public function array(): array
    {
        // GET_FZT_PAYMENT_ORDER_STATUS_LIST:XXXXXX
        $llen = Redis::llen('GET_FZT_PAYMENT_ORDER_STATUS_LIST:' . $this->batchNumber);
        if ($llen === 0) {
            return [];
        }

        $perPage = 1000;
        $list = [];
        for ($i = 0; $i < ceil($llen / $perPage); $i ++) {
            foreach ((array) Redis::lrange('GET_FZT_PAYMENT_ORDER_STATUS_LIST:' . $this->batchNumber, ($i - 1) * $perPage, $perPage) as $item) {
                $temp = json_decode($item, true);
                // 这里是为了重新排序 对应 headings
                $list[] = [
                    $temp['order_id'],
                    $temp['agent_name'],
                    $temp['agent_real_name'],
                    $temp['agent_phone'],
                    self::STAT_MAP[$temp['stat']],
                    AgentTopUpOrder::STATUS_MAP[$temp['status']],
                ];
            }
        }

        return $list;
    }

    public function bindValue(Cell $cell, $value)
    {
        $cell->setValueExplicit($value, DataType::TYPE_STRING);

        return true;
    }
}
